//
//  ScannerView.m
//  CarCare
//
//  Created by ileo on 14-8-18.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "ScannerView.h"

@interface ScannerView()

@property (nonatomic, assign) CGRect scanRect;

@end

@implementation ScannerView

- (id)initWithFrame:(CGRect)frame withScanRect:(CGRect)scanRect{
	if (self = [super initWithFrame:frame]) {
		self.backgroundColor = [UIColor clearColor];
        
        self.scanRect = scanRect;
        UIImageView *borderView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"border"]];
        borderView.frame=CGRectMake(scanRect.origin.x-5, scanRect.origin.y-5, SCANNER_WIDTH+10, SCANNER_WIDTH+10);
        [self addSubview:borderView];
        //扫描线
        self.lineView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"line"]];
        self.lineView.frame=CGRectMake(scanRect.origin.x, scanRect.origin.y, SCANNER_WIDTH, 2);
        [self addSubview:self.lineView];
        
        [Factory labelWithFrame:CGRectMake(0, borderView.bottom + 40, frame.size.width, 40) font:[UIFont systemFontOfSize:13] text:@"请将设备上的条形码放入扫描框内" textColor:[UIColor whiteColor] onView:self textAlignment:NSTextAlignmentCenter];
	}
	return self;
}

/**
 *  扫描线动画
 */
- (void)lineAnimation {
    
    [self.lineView.layer removeAllAnimations];
	CGPoint startPoint = CGPointMake(self.scanRect.origin.x+SCANNER_WIDTH/2, self.scanRect.origin.y);
	CGPoint endPoint = CGPointMake(self.scanRect.origin.x+SCANNER_WIDTH/2, self.scanRect.origin.y+SCANNER_WIDTH);
	CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
	animation.fromValue = [NSValue valueWithCGPoint:startPoint];
	animation.toValue = [NSValue valueWithCGPoint:endPoint];
	animation.duration = 2.f;
	animation.autoreverses = YES;
	animation.repeatCount = HUGE_VALF;
	[self.lineView.layer addAnimation:animation forKey:nil];
}

/**
 *  移除动画
 */
- (void)removeLineAnimation {
	[self.lineView.layer removeAllAnimations];
}

/**
 *  增加阴影
 *
 *  @param rect rect
 */
- (void)drawRect:(CGRect)rect {
	float x = self.scanRect.origin.x;
    float y = self.scanRect.origin.y;
    float width = self.scanRect.size.width;
    float height = self.scanRect.size.height;
    float mainWidth = self.frame.size.width;
    float mainHeight = self.frame.size.height;
	
	CGContextRef ctx = UIGraphicsGetCurrentContext();
	CGContextSetFillColorWithColor(ctx, [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5f].CGColor);
	CGContextFillRect(ctx,CGRectMake(0, 0, mainWidth, y));
	CGContextFillRect(ctx,CGRectMake(0, y, x, height));
	CGContextFillRect(ctx,CGRectMake(x+width, y, mainWidth-x-width, height));
	CGContextFillRect(ctx,CGRectMake(0, y+height, mainWidth, mainHeight-y-height));
    
}



@end
